package com.station.service.impl;

import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.RepoResult;
import com.station.entity.KingErpBillRecord;
import com.station.enums.ErpOrderTypeEnum;
import com.station.param.request.receipt.FRECEIVEBILLENTRY;
import com.station.param.request.receipt.ReceiptRequest;
import com.station.param.request.saleorder.*;
import com.station.param.request.saleorder.Model;
import com.station.param.request.salereturn.*;
import com.station.service.KingErpBillRecordService;
import com.station.service.SaleOrderService;
import com.station.service.mapper.ItemMapper;
import com.station.service.mapper.SaleOrderMapper;
import com.station.service.mapper.UnitMapper;
import com.station.utils.DateUtils;
import com.station.utils.KingDeeUtils;
import com.station.utils.R;
import com.station.utils.StringUtils;
import com.station.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: dongfangyu
 * @Date: 2025/10/11
 */
@Slf4j
@Service
public class SaleOrderServiceImpl implements SaleOrderService {

    @Autowired
    private SaleOrderMapper saleOrderMapper;
    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private KingErpBillRecordService kingErpBillRecordService;

    @Value("${rd.bld.vendorId}")
    private String vendorId;
    @Value("${rd.kingdee.bzOrderType}")
    private String bzOrderType;
    @Value("${rd.kingdee.b2cOrderType}")
    private String b2cOrderType;
    @Value("${rd.kingdee.FCustId}")
    private String FCustId;
    @Value("${rd.kingdee.FSalerId}")
    private String FSalerId;
    @Value("${rd.kingdee.reOrderType}")
    private String reOrderType;


    private static final String F_SALE_ORG_ID = "100";
    /**
     * 分组前缀
     */
    private static final String F_GROUP_PREFIX = "03.13";
    /**
     * 服务类商品-优惠券
     */
    private static final String F_COUPON = "03.13.60.001";
    /**
     * 销售订单批量保存业务标识
     */
    private static final String FormId_SaleOrder = "SAL_SaleOrder";
    /**
     * 销售退货单批量保存业务标识
     */
    private static final String FormId_SaleRefundOrder = "SAL_RETURNSTOCK";

    /**
     * 收款单批量保存业务标识
     */
    private static final String FormId_Receive ="AR_RECEIVEBILL";
    /**
     * 客户业务标识
     */
    private static final String BD_CUSTOMER = "BD_Customer";
    /**
     * 币别业务标识
     */
    private static final String CURRENCY_TYPE = "PRE001";
    /**
     * 仓库前缀
     */
    private static final String STORE_PREFIX = "bld";
    /**
     * 便利店支付方式-现金
     */
    private static final String PAY_TYPE_CASH = "204007CASH";
    /**
     * 便利店支付方式-优惠券
     */
    private static final String PAY_TYPE_COUPON = "204007SHP";
    /**
     * 便利店支付方式-银行卡
     */
    private static final String PAY_TYPE_CARD = "204007CRD";
    /**
     * 便利店支付方式-微信
     */
    private static final String PAY_TYPE_WECHAT = "204007CIBPay_WeChat";
    /**
     * 便利店支付方式-支付宝
     */
    private static final String PAY_TYPE_ALIPAY = "204007CIBPay_AliPay";
    /**
     * 便利店单位
     */
    private static final String BLD_UNIT = "CUST0067";

    @Override
    public R syncSaleOrder(String startDate, String endDate) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            String[] perDate = DateUtils.getPerDate();
            startDate = perDate[0];
            endDate = perDate[1];
        }
        List<SaleOrder> saleOrders = querySaleOrderList(startDate, endDate);
        List<KingErpBillRecord> records = new ArrayList<>();
        if (!CollectionUtils.isEmpty(saleOrders)) {
            Model[] models = new Model[saleOrders.size()];
            int index = 0;
            for (SaleOrder saleOrder : saleOrders) {
                List<OrderDetail> orderDetailList = saleOrder.getOrderDetailList();
                SaleOrderEntry[] saleOrderEntries = new SaleOrderEntry[orderDetailList.size()];
                int detailIndex = 0;
                for (OrderDetail orderDetail : orderDetailList) {
                    //拼接明细数据
                    UnitVo unitVo = unitMapper.queryUnitByCondition(Long.valueOf(vendorId), orderDetail.getSaleUnit());
                    String unitCode = "Pcs";
                    if (null != unitVo && null != unitVo.getUnitCode()) {
                        unitCode = unitVo.getUnitCode();
                    }
                    SaleOrderEntry saleOrderEntry = new SaleOrderEntry();
                    ItemVo itemVo = itemMapper.queryItemBySkuCode(Long.valueOf(vendorId), orderDetail.getSkuCode());
                    String cartId = null;
                    if (StringUtils.isEmpty(itemVo.getParentCode())) {
                        cartId = itemVo.getCatCode();
                    } else {
                        cartId = itemVo.getParentCode() + "." + itemVo.getCatCode();
                    }
                    saleOrderEntry.setFMaterialId(new FMaterialId(F_GROUP_PREFIX + "." + cartId + "." + itemVo.getItemId()));
                    saleOrderEntry.setFUnitID(new FUnitID(unitCode));
                    saleOrderEntry.setFPriceUnitId(new FPriceUnitId(unitCode));
                    saleOrderEntry.setFDeliveryDate(orderDetail.getCreateDate());
                    saleOrderEntry.setFSettleOrgIds(new FSettleOrgIds(F_SALE_ORG_ID));
                    saleOrderEntry.setFReserveType("1");
                    saleOrderEntry.setFStockUnitID(new FStockUnitID(unitCode));
                    saleOrderEntry.setFOUTLMTUNIT("销售单位");
                    saleOrderEntry.setFQty(orderDetail.getSkuNum());
                    saleOrderEntry.setFPrice(orderDetail.getSalePrice());
                    saleOrderEntry.setFTaxPrice(orderDetail.getSalePrice());
                    saleOrderEntry.setFEntryTaxRate(0);
                    saleOrderEntry.setFSOStockId(new FSOStockId(STORE_PREFIX + saleOrder.getOrderStore()));
                    //明细折扣
                    if (null != orderDetail.getPreAmount() && orderDetail.getPreAmount().compareTo(BigDecimal.ZERO) > 0){
                        //折扣额
                        saleOrderEntry.setFDiscount(orderDetail.getPreAmount());
                        //单价折扣
                        saleOrderEntry.setFPriceDiscount(orderDetail.getPreAmount().divide(BigDecimal.valueOf(orderDetail.getSkuNum())).setScale(2, RoundingMode.HALF_UP));
                        //折扣率%
                        saleOrderEntry.setFDiscountRate(orderDetail.getDiscount());
                    }
                    saleOrderEntries[detailIndex++] = saleOrderEntry;
                }
                //拼接订单数据
                Model model = new Model();
                model.setFBillNo(saleOrder.getOrderNo());
                model.setFBillTypeID(new FBillTypeID(bzOrderType));
                model.setFDate(saleOrder.getCreateDate());
                model.setFSaleOrgId(new FSaleOrgId(F_SALE_ORG_ID));
                model.setFCustId(new FCustId(FCustId));
                model.setFSalerId(new FSalerId(FSalerId));
                model.setFSaleOrderEntry(saleOrderEntries);
                //整单折扣率
                if (null != saleOrder.getCouponAmount() && saleOrder.getCouponAmount().compareTo(BigDecimal.ZERO) > 0){
                    FSaleOrderFinance fSaleOrderFinance = new FSaleOrderFinance();
                    fSaleOrderFinance.setFAllDisCount(saleOrder.getRealPayAmount().divide(saleOrder.getOrderAmount(),2, RoundingMode.HALF_UP));
                    model.setFSaleOrderFinance(fSaleOrderFinance);
                }
                //关联收款单
                FSaleOrderPlan fSaleOrderPlan = new FSaleOrderPlan();
                fSaleOrderPlan.setFNeedRecAdvance(true);
                fSaleOrderPlan.setFRelBillNo("PRE" + saleOrder.getOrderNo());
                model.setFSaleOrderPlan(new FSaleOrderPlan[]{fSaleOrderPlan});
                models[index++] = model;

                KingErpBillRecord billRecord = KingErpBillRecord.builder().
                        billDate(DateUtils.formatStringToDate(saleOrder.getCreateDate())).billType(ErpOrderTypeEnum.ERP_ORDER_TYPE_5.getValue().toString())
                        .orderNo(saleOrder.getOrderNo()).createTime(new Date()).stationId(Long.valueOf(saleOrder.getOrderStore())).isDel(0).build();
                records.add(billRecord);
            }
            //同步销售订单数据到金蝶
            SaleOrderBatchRequest saleOrderRequest = new SaleOrderBatchRequest();
            saleOrderRequest.setModel(models);
            /*saleOrderRequest.setIsAutoSubmitAndAudit(true);*/
            Gson requestGson = new Gson();
            String requestJson = requestGson.toJson(saleOrderRequest);
            RepoResult repoResult = KingDeeUtils.batchSave(FormId_SaleOrder, requestJson);
            if (repoResult.getResponseStatus().isIsSuccess()) {
                for (KingErpBillRecord record : records) {
                    record.setStatus(1);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.ok().put("data", repoResult.getResult());
            } else {
                String msg = KingDeeUtils.toErrorMessageString(repoResult.getResponseStatus().getErrors());
                for (KingErpBillRecord record : records) {
                    record.setStatus(0);
                    record.setResponText(msg);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.error(msg);
            }
        }
        return R.ok("未查询到订单数据！");
    }

    @Override
    public R syncSaleReceipt(String startDate, String endDate) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            String[] perDate = DateUtils.getPerDate();
            startDate = perDate[0];
            endDate = perDate[1];
        }
        List<SaleOrder> saleOrders = saleOrderMapper.querySaleOrderList(Long.valueOf(vendorId), startDate, endDate);
        List<KingErpBillRecord> records = new ArrayList<>();
        if (!CollectionUtils.isEmpty(saleOrders)) {
            com.station.param.request.receipt.Model[] models = new com.station.param.request.receipt.Model[saleOrders.size()];
            int index = 0;
            for (SaleOrder saleOrder : saleOrders) {
                List<SalePay> salePayList = saleOrderMapper.queryOrderPayWayList(saleOrder.getOrderNo());
                FRECEIVEBILLENTRY[] receiveBillEntries = new FRECEIVEBILLENTRY[salePayList.size()];
                if (!CollectionUtils.isEmpty(salePayList)) {
                    int detailIndex = 0;
                    for (SalePay salePay : salePayList) {
                        FRECEIVEBILLENTRY receiveBillEntry = new FRECEIVEBILLENTRY();
                        switch (salePay.getPayCode()){
                            case PAY_TYPE_CASH:
                                receiveBillEntry.setFsettletypeid(new com.station.param.request.receipt.FSETTLETYPEID("bld.cash"));
                                break;
                            case PAY_TYPE_COUPON:
                                receiveBillEntry.setFsettletypeid(new com.station.param.request.receipt.FSETTLETYPEID("bld.coupon"));
                                break;
                            case PAY_TYPE_CARD:
                                receiveBillEntry.setFsettletypeid(new com.station.param.request.receipt.FSETTLETYPEID("bld.card"));
                                break;
                            case PAY_TYPE_WECHAT:
                                receiveBillEntry.setFsettletypeid(new com.station.param.request.receipt.FSETTLETYPEID("bld.wechat"));
                                break;
                            case PAY_TYPE_ALIPAY:
                                receiveBillEntry.setFsettletypeid(new com.station.param.request.receipt.FSETTLETYPEID("bld.alipay"));
                                break;
                            default:
                                break;
                        }
                        receiveBillEntry.setFpurposeid(new com.station.param.request.receipt.FPURPOSEID("SFKYT02_SYS"));
                        receiveBillEntry.setFPOSTDATE(saleOrder.getCreateDate());
                        receiveBillEntry.setFRECTOTALAMOUNTFOR(salePay.getRealPayAmount());
                        receiveBillEntries[detailIndex++] = receiveBillEntry;
                    }
                }
                com.station.param.request.receipt.Model model = new com.station.param.request.receipt.Model();
                model.setFBillTypeID(new com.station.param.request.receipt.FBillTypeID(reOrderType));
                model.setFBillNo("PRE" + saleOrder.getOrderNo());
                model.setFDATE(saleOrder.getCreateDate());
                model.setFCONTACTUNITTYPE(BD_CUSTOMER);
                model.setFcontactunit(new com.station.param.request.receipt.FCONTACTUNIT(BLD_UNIT));
                model.setFPAYUNITTYPE(BD_CUSTOMER);
                model.setFPAYUNIT(new com.station.param.request.receipt.FPAYUNIT(BLD_UNIT));
                model.setFcurrencyid(new com.station.param.request.receipt.FCURRENCYID(CURRENCY_TYPE));
                model.setFsettlecur(new com.station.param.request.receipt.FSETTLECUR(CURRENCY_TYPE));
                //单据状态 A 创建 B 审核中 C 已审核 D 重新审核
                model.setFDOCUMENTSTATUS("C");
                //业务类型
                model.setFBUSINESSTYPE("1");
                //作废状态
                model.setFCancelStatus("A");
                //结算本位币
                model.setFsettlemainbookid(new com.station.param.request.receipt.FSETTLEMAINBOOKID(CURRENCY_TYPE));
                model.setFreceivebillentry(receiveBillEntries);
                model.setFPAYORGID(new com.station.param.request.receipt.FPAYORGID(F_SALE_ORG_ID));
                models[index++] = model;

                KingErpBillRecord billRecord = KingErpBillRecord.builder().
                        billDate(DateUtils.formatStringToDate(saleOrder.getCreateDate())).billType(ErpOrderTypeEnum.ERP_ORDER_TYPE_8.getValue().toString())
                        .orderNo(saleOrder.getOrderNo()).createTime(new Date()).stationId(Long.valueOf(saleOrder.getOrderStore())).isDel(0).build();
                records.add(billRecord);
            }
            ReceiptRequest receiptRequest = new ReceiptRequest();
            receiptRequest.setModel(models);
            receiptRequest.setIsAutoSubmitAndAudit(true);
            Gson requestGson = new Gson();
            String requestJson = requestGson.toJson(receiptRequest);
            RepoResult repoResult = KingDeeUtils.batchSave(FormId_Receive, requestJson);
            if (repoResult.getResponseStatus().isIsSuccess()) {
                for (KingErpBillRecord record : records) {
                    record.setStatus(1);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.ok().put("data", repoResult.getResult());
            } else {
                String msg = KingDeeUtils.toErrorMessageString(repoResult.getResponseStatus().getErrors());
                for (KingErpBillRecord record : records) {
                    record.setStatus(0);
                    record.setResponText(msg);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.error(msg);
            }
        }
        return R.ok("未查询到订单数据！");
    }

    @Override
    public R syncReceipt(String startDate, String endDate) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            String[] perDate = DateUtils.getPerDate();
            startDate = perDate[0];
            endDate = perDate[1];
        }
        List<SaleOrder> saleOrders = queryWaitVerifyOrderList(startDate, endDate);
        List<KingErpBillRecord> records = new ArrayList<>();
        if (!CollectionUtils.isEmpty(saleOrders)) {
            com.station.param.request.receipt.Model[] models = new com.station.param.request.receipt.Model[saleOrders.size()];
            int index = 0;
            for (SaleOrder saleOrder : saleOrders) {
                List<SalePay> salePayList = saleOrderMapper.queryOrderPayWayList(saleOrder.getOrderNo());
                //List<OrderDetail> orderDetailList = saleOrder.getOrderDetailList();
                FRECEIVEBILLENTRY[] receiveBillEntries = new FRECEIVEBILLENTRY[salePayList.size()];
                int detailIndex = 0;
                for (SalePay salePay : salePayList) {
                    FRECEIVEBILLENTRY receiveBillEntry = new FRECEIVEBILLENTRY();
                    switch (salePay.getPayCode()){
                        case PAY_TYPE_CASH:
                            receiveBillEntry.setFsettletypeid(new com.station.param.request.receipt.FSETTLETYPEID("bld.cash"));
                            break;
                        case PAY_TYPE_COUPON:
                            receiveBillEntry.setFsettletypeid(new com.station.param.request.receipt.FSETTLETYPEID("bld.coupon"));
                            break;
                        case PAY_TYPE_CARD:
                            receiveBillEntry.setFsettletypeid(new com.station.param.request.receipt.FSETTLETYPEID("bld.card"));
                            break;
                        case PAY_TYPE_WECHAT:
                            receiveBillEntry.setFsettletypeid(new com.station.param.request.receipt.FSETTLETYPEID("bld.wechat"));
                            break;
                        case PAY_TYPE_ALIPAY:
                            receiveBillEntry.setFsettletypeid(new com.station.param.request.receipt.FSETTLETYPEID("bld.alipay"));
                            break;
                        default:
                            break;
                    }
                    receiveBillEntry.setFpurposeid(new com.station.param.request.receipt.FPURPOSEID("SFKYT02_SYS"));
                    receiveBillEntry.setFPOSTDATE(saleOrder.getCreateDate());
                    receiveBillEntry.setFRECTOTALAMOUNTFOR(salePay.getRealPayAmount());
                    /*ItemVo itemVo = itemMapper.queryItemBySkuCode(Long.valueOf(vendorId), orderDetail.getSkuCode());
                    String cartId = null;
                    if (StringUtils.isEmpty(itemVo.getParentCode())) {
                        cartId = itemVo.getCatCode();
                    } else {
                        cartId = itemVo.getParentCode() + "." + itemVo.getCatCode();
                    }
                    receiveBillEntry.setFmaterialid(new com.station.param.request.receipt.FMATERIALID(F_GROUP_PREFIX + "." + cartId + "." + itemVo.getItemId()));
                    receiveBillEntry.setFQty(orderDetail.getSkuNum());
                    receiveBillEntry.setFRECTOTALAMOUNTFOR(orderDetail.getAmount());
                    receiveBillEntry.setFRECAMOUNTFOR_E(orderDetail.getSalePrice());*/

                    receiveBillEntries[detailIndex++] = receiveBillEntry;
                }
                //拼接订单数据
                com.station.param.request.receipt.Model model = new com.station.param.request.receipt.Model();
                model.setFBillTypeID(new com.station.param.request.receipt.FBillTypeID(reOrderType));
                model.setFBillNo("PRE"+saleOrder.getOrderNo());
                model.setFDATE(saleOrder.getCreateDate());
                model.setFCONTACTUNITTYPE(BD_CUSTOMER);
                model.setFcontactunit(new com.station.param.request.receipt.FCONTACTUNIT(BLD_UNIT));
                model.setFPAYUNITTYPE(BD_CUSTOMER);
                model.setFPAYUNIT(new com.station.param.request.receipt.FPAYUNIT(BLD_UNIT));
                model.setFcurrencyid(new com.station.param.request.receipt.FCURRENCYID(CURRENCY_TYPE));
                model.setFsettlecur(new com.station.param.request.receipt.FSETTLECUR(CURRENCY_TYPE));
                //单据状态 A 创建 B 审核中 C 已审核 D 重新审核
                model.setFDOCUMENTSTATUS("C");
                //业务类型
                model.setFBUSINESSTYPE("1");
                //作废状态
                model.setFCancelStatus("A");
                //结算本位币
                model.setFsettlemainbookid(new com.station.param.request.receipt.FSETTLEMAINBOOKID(CURRENCY_TYPE));
                model.setFreceivebillentry(receiveBillEntries);
                models[index++] = model;

                KingErpBillRecord billRecord = KingErpBillRecord.builder().
                        billDate(DateUtils.formatStringToDate(saleOrder.getCreateDate())).billType(ErpOrderTypeEnum.ERP_ORDER_TYPE_8.getValue().toString())
                        .orderNo(saleOrder.getOrderNo()).createTime(new Date()).stationId(Long.valueOf(saleOrder.getOrderStore())).isDel(0).build();
                records.add(billRecord);
            }
            ReceiptRequest receiptRequest = new ReceiptRequest();
            receiptRequest.setModel(models);
            receiptRequest.setIsAutoSubmitAndAudit(true);
            Gson requestGson = new Gson();
            String requestJson = requestGson.toJson(receiptRequest);
            RepoResult repoResult = KingDeeUtils.batchSave(FormId_Receive, requestJson);
            if (repoResult.getResponseStatus().isIsSuccess()) {
                for (KingErpBillRecord record : records) {
                    record.setStatus(1);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.ok().put("data", repoResult.getResult());
            } else {
                String msg = KingDeeUtils.toErrorMessageString(repoResult.getResponseStatus().getErrors());
                for (KingErpBillRecord record : records) {
                    record.setStatus(0);
                    record.setResponText(msg);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.error(msg);
            }
        }
        return R.ok("未查询到订单数据！");
    }

    @Override
    public R syncVerifyOrder(String startDate, String endDate) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            String[] perDate = DateUtils.getPerDate();
            startDate = perDate[0];
            endDate = perDate[1];
        }
        List<SaleOrder> saleOrders = queryVerifyOrderList(startDate, endDate);
        List<KingErpBillRecord> records = new ArrayList<>();
        if(!CollectionUtils.isEmpty(saleOrders)) {
            Model[] models = new Model[saleOrders.size()];
            int index = 0;
            for (SaleOrder saleOrder : saleOrders) {
                List<OrderDetail> orderDetailList = saleOrder.getOrderDetailList();
                SaleOrderEntry[] saleOrderEntries = new SaleOrderEntry[orderDetailList.size()];
                int detailIndex = 0;
                for (OrderDetail orderDetail : orderDetailList) {
                    UnitVo unitVo = unitMapper.queryUnitByCondition(Long.valueOf(vendorId), orderDetail.getSaleUnit());
                    String unitCode = "Pcs";
                    if (null != unitVo && null != unitVo.getUnitCode()) {
                        unitCode = unitVo.getUnitCode();
                    }
                    SaleOrderEntry saleOrderEntry = new SaleOrderEntry();
                    ItemVo itemVo = itemMapper.queryItemBySkuCode(Long.valueOf(vendorId), orderDetail.getSkuCode());
                    String cartId = null;
                    if (StringUtils.isEmpty(itemVo.getParentCode())) {
                        cartId = itemVo.getCatCode();
                    } else {
                        cartId = itemVo.getParentCode() + "." + itemVo.getCatCode();
                    }
                    saleOrderEntry.setFMaterialId(new FMaterialId(F_GROUP_PREFIX + "." + cartId + "." + itemVo.getItemId()));
                    saleOrderEntry.setFUnitID(new FUnitID(unitCode));
                    saleOrderEntry.setFPriceUnitId(new FPriceUnitId(unitCode));
                    saleOrderEntry.setFDeliveryDate(orderDetail.getCreateDate());
                    saleOrderEntry.setFSettleOrgIds(new FSettleOrgIds(F_SALE_ORG_ID));
                    saleOrderEntry.setFReserveType("1");
                    saleOrderEntry.setFStockUnitID(new FStockUnitID(unitCode));
                    saleOrderEntry.setFOUTLMTUNIT("销售单位");
                    saleOrderEntry.setFQty(orderDetail.getSkuNum());
                    saleOrderEntry.setFPrice(orderDetail.getSalePrice());
                    saleOrderEntry.setFTaxPrice(orderDetail.getSalePrice());
                    saleOrderEntry.setFEntryTaxRate(0);
                    saleOrderEntry.setFSOStockId(new FSOStockId(STORE_PREFIX + saleOrder.getOrderStore()));
                    saleOrderEntries[detailIndex++] = saleOrderEntry;
                }
                //拼接订单数据
                Model model = new Model();
                model.setFBillNo(saleOrder.getOrderNo());
                model.setFBillTypeID(new FBillTypeID(b2cOrderType));
                model.setFDate(saleOrder.getCreateDate());
                model.setFSaleOrgId(new FSaleOrgId(F_SALE_ORG_ID));
                model.setFCustId(new FCustId(FCustId));
                model.setFSalerId(new FSalerId(FSalerId));
                model.setFSaleOrderEntry(saleOrderEntries);
                models[index++] = model;

                KingErpBillRecord billRecord = KingErpBillRecord.builder().
                        billDate(DateUtils.formatStringToDate(saleOrder.getCreateDate())).billType(ErpOrderTypeEnum.ERP_ORDER_TYPE_5.getValue().toString())
                        .orderNo(saleOrder.getOrderNo()).createTime(new Date()).stationId(Long.valueOf(saleOrder.getOrderStore())).isDel(0).build();
                records.add(billRecord);
            }
            //同步销售订单数据到金蝶
            SaleOrderBatchRequest saleOrderRequest = new SaleOrderBatchRequest();
            saleOrderRequest.setModel(models);
            saleOrderRequest.setIsAutoSubmitAndAudit(true);
            Gson requestGson = new Gson();
            String requestJson = requestGson.toJson(saleOrderRequest);
            RepoResult repoResult = KingDeeUtils.batchSave(FormId_SaleOrder, requestJson);
            if (repoResult.getResponseStatus().isIsSuccess()) {
                for (KingErpBillRecord record : records) {
                    record.setStatus(1);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.ok().put("data", repoResult.getResult());
            } else {
                String msg = KingDeeUtils.toErrorMessageString(repoResult.getResponseStatus().getErrors());
                for (KingErpBillRecord record : records) {
                    record.setStatus(0);
                    record.setResponText(msg);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.error(msg);
            }
        }
        return R.ok("未查询到订单数据！");
    }

    @Override
    public R syncRefundOrder(String startDate, String endDate) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            String[] perDate = DateUtils.getPerDate();
            startDate = perDate[0];
            endDate = perDate[1];
        }
        List<SaleOrder> saleOrders = querySaleRefundOrderList(startDate, endDate);
        List<KingErpBillRecord> records = new ArrayList<>();
        if(!CollectionUtils.isEmpty(saleOrders)) {
            com.station.param.request.salereturn.Model[] models = new com.station.param.request.salereturn.Model[saleOrders.size()];
            int index = 0;
            for (SaleOrder saleOrder : saleOrders) {
                List<OrderDetail> orderDetailList = saleOrder.getOrderDetailList();
                int detailIndex = 0;
                FEntity[] fEntities = new FEntity[orderDetailList.size() + 1];
                for (OrderDetail orderDetail : orderDetailList) {
                    UnitVo unitVo = unitMapper.queryUnitByCondition(Long.valueOf(vendorId), orderDetail.getSaleUnit());
                    String unitCode = "Pcs";
                    if (null != unitVo && null != unitVo.getUnitCode()) {
                        unitCode = unitVo.getUnitCode();
                    }
                    ItemVo itemVo = itemMapper.queryItemBySkuCode(Long.valueOf(vendorId), orderDetail.getSkuCode());
                    String cartId = null;
                    if (StringUtils.isEmpty(itemVo.getParentCode())) {
                        cartId = itemVo.getCatCode();
                    } else {
                        cartId = itemVo.getParentCode() + "." + itemVo.getCatCode();
                    }
                    FEntity fEntity = new FEntity();
                    fEntity.setFSrcBillNo(saleOrder.getOrigNo());
                    fEntity.setFSrcBillTypeID("SAL_SaleOrder");
                    fEntity.setFRowType("Standard");
                    fEntity.setFMaterialId(new FMaterialId(F_GROUP_PREFIX + "." + cartId + "." + itemVo.getItemId()));
                    fEntity.setFUnitID(new FUnitID(unitCode));
                    fEntity.setFRealQty(Math.abs(orderDetail.getSkuNum()));
                    fEntity.setFPrice(orderDetail.getRealPrice());
                    fEntity.setFTaxPrice(orderDetail.getRealPrice());
                    fEntity.setFAmount(orderDetail.getAmount().abs());
                    fEntity.setFEntryTaxRate(0);
                    fEntity.setFIsFree(false);
                    fEntity.setFReturnType(new FReturnType("THLX01_SYS"));
                    fEntity.setFOwnerTypeId("BD_OwnerOrg");
                    fEntity.setFOwnerId(new FOwnerId(F_SALE_ORG_ID));
                    fEntity.setFStockId(new FStockId(STORE_PREFIX + saleOrder.getOrderStore()));
                    fEntity.setFStockstatusId(new FStockstatusId("KCZT01_SYS"));
                    fEntity.setFDeliveryDate(orderDetail.getCreateDate());
                    fEntity.setFSalUnitID(new FSalUnitID(unitCode));
                    fEntity.setFSalUnitQty(Math.abs(orderDetail.getSkuNum()));
                    fEntity.setFSalBaseQty(Math.abs(orderDetail.getSkuNum()));
                    fEntity.setFPriceBaseQty(Math.abs(orderDetail.getSkuNum()));
                    fEntity.setFIsOverLegalOrg(false);
                    fEntity.setFARNOTJOINQTY(Math.abs(orderDetail.getSkuNum()));
                    fEntity.setFIsReturnCheck(false);
                    fEntity.setFSettleBySon(false);
                    fEntity.setFMaterialID_Sal(new FMaterialID_Sal(F_GROUP_PREFIX + "." + cartId + "." + itemVo.getItemId()));
                    fEntity.setFINSTOCKDATE(orderDetail.getCreateDate());
                    fEntities[detailIndex++] = fEntity;
                    if (null != itemVo && itemVo.getItemType() == 3 ){
                        if (orderDetail.getAmount().abs().compareTo(orderDetail.getRealPrice().multiply(new BigDecimal(Math.abs(orderDetail.getSkuNum())))) < 0){
                            FEntity virtualCouponEntity = new FEntity();
                            virtualCouponEntity.setFSrcBillNo(saleOrder.getOrigNo());
                            virtualCouponEntity.setFSrcBillTypeID("SAL_SaleOrder");
                            virtualCouponEntity.setFRowType("Standard");
                            virtualCouponEntity.setFMaterialId(new FMaterialId(F_COUPON));
                            virtualCouponEntity.setFRealQty(1);
                            virtualCouponEntity.setFEntryTaxRate(0);
                            virtualCouponEntity.setFAmount(orderDetail.getRealPrice().subtract(orderDetail.getAmount().abs()));
                            virtualCouponEntity.setFIsFree(false);
                            virtualCouponEntity.setFReturnType(new FReturnType("THLX01_SYS"));
                            virtualCouponEntity.setFOwnerTypeId("BD_OwnerOrg");
                            virtualCouponEntity.setFOwnerId(new FOwnerId(F_SALE_ORG_ID));
                            virtualCouponEntity.setFStockId(new FStockId(STORE_PREFIX + saleOrder.getOrderStore()));
                            virtualCouponEntity.setFStockstatusId(new FStockstatusId("KCZT01_SYS"));
                            virtualCouponEntity.setFDeliveryDate(orderDetail.getCreateDate());
                            fEntities[detailIndex++] = virtualCouponEntity;
                        }
                    }
                }
                com.station.param.request.salereturn.Model model = new com.station.param.request.salereturn.Model();
                model.setFBillNo(saleOrder.getOrderNo());
                model.setFBillTypeID(new FBillTypeID("XSTHD01_SYS"));
                model.setFDate(saleOrder.getModifyDate());
                model.setFSaleOrgId(new FSaleOrgId(F_SALE_ORG_ID));
                model.setFRetcustId(new FRetcustId(BLD_UNIT));
                model.setFTransferBizType(new FTransferBizType("OverOrgSal"));
                model.setFStockOrgId(new FStockOrgId(F_SALE_ORG_ID));
                model.setFReceiveCustId(new FReceiveCustId(BLD_UNIT));
                model.setFRetcustId(new FRetcustId(BLD_UNIT));
                model.setFSettleCustId(new FSettleCustId(BLD_UNIT));
                model.setFPayCustId(new FPayCustId(BLD_UNIT));
                model.setFOwnerTypeIdHead("BD_OwnerOrg");
                model.setFCDateOffsetValue(0);
                model.setFIsTotalServiceOrCost(false);
                model.setFAllRefundNoGoods(false);
                model.setFEntity(fEntities);
                SubHeadEntity subHeadEntity = new SubHeadEntity();
                subHeadEntity.setFSettleCurrId(new FSettleCurrId(CURRENCY_TYPE));
                subHeadEntity.setFSettleOrgId(new FSettleOrgId(F_SALE_ORG_ID));
                subHeadEntity.setFLocalCurrId(new FLocalCurrId(CURRENCY_TYPE));
                subHeadEntity.setFExchangeTypeId(new FExchangeTypeId("XJLX01_SYS"));
                model.setSubHeadEntity(subHeadEntity);
                models[index++] = model;

                KingErpBillRecord billRecord = KingErpBillRecord.builder().
                        billDate(DateUtils.formatStringToDate(saleOrder.getCreateDate())).billType(ErpOrderTypeEnum.ERP_ORDER_TYPE_6.getValue().toString())
                        .orderNo(saleOrder.getOrderNo()).createTime(new Date()).stationId(Long.valueOf(saleOrder.getOrderStore())).isDel(0).build();
                records.add(billRecord);
            }
            SaleReturnRequest saleReturnRequest = new SaleReturnRequest();
            saleReturnRequest.setModel(models);
            saleReturnRequest.setIsAutoSubmitAndAudit(true);
            Gson requestGson = new Gson();
            String requestJson = requestGson.toJson(saleReturnRequest);
            RepoResult repoResult = KingDeeUtils.batchSave(FormId_SaleRefundOrder, requestJson);
            if (repoResult.getResponseStatus().isIsSuccess()) {
                for (KingErpBillRecord record : records) {
                    record.setStatus(1);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.ok().put("data", repoResult.getResult());
            } else {
                String msg = KingDeeUtils.toErrorMessageString(repoResult.getResponseStatus().getErrors());
                for (KingErpBillRecord record : records) {
                    record.setStatus(0);
                    record.setResponText(msg);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.error(msg);
            }
        }
        return R.ok("未查询到退货订单数据！");
    }

    @Override
    public List<SaleOrder> querySaleOrderList(String startDate, String endDate) {
        List<SaleOrder> saleOrders = new ArrayList<>();
        saleOrders = saleOrderMapper.querySaleOrderList(Long.valueOf(vendorId), startDate, endDate);
        if (!CollectionUtils.isEmpty(saleOrders)) {
            for (SaleOrder saleOrder : saleOrders) {
                List<OrderDetail> orderDetails = saleOrderMapper.queryOrderDetailList(saleOrder.getOrderNo());
                if (!CollectionUtils.isEmpty(orderDetails)) {
                    saleOrder.setOrderDetailList(orderDetails);
                }
            }
        }
        return saleOrders;
    }

    @Override
    public List<SaleOrder> queryWaitVerifyOrderList(String startDate, String endDate) {
        List<SaleOrder> saleOrders = new ArrayList<>();
        saleOrders = saleOrderMapper.queryWaitVerifyOrderList(Long.valueOf(vendorId), startDate, endDate);
        if (!CollectionUtils.isEmpty(saleOrders)) {
            for (SaleOrder saleOrder : saleOrders) {
                List<OrderDetail> orderDetails = saleOrderMapper.queryOrderDetailList(saleOrder.getOrderNo());
                if (!CollectionUtils.isEmpty(orderDetails)) {
                    saleOrder.setOrderDetailList(orderDetails);
                }
            }
        }
        return saleOrders;
    }

    @Override
    public List<SaleOrder> queryVerifyOrderList(String startDate, String endDate) {
        List<SaleOrder> saleOrders = new ArrayList<>();
        saleOrders = saleOrderMapper.queryVerifyOrderList(startDate, endDate);
        if (!CollectionUtils.isEmpty(saleOrders)) {
            for (SaleOrder saleOrder : saleOrders) {
                List<OrderDetail> orderDetails = saleOrderMapper.queryOrderDetailList(saleOrder.getOrderNo());
                if (!CollectionUtils.isEmpty(orderDetails)) {
                    saleOrder.setOrderDetailList(orderDetails);
                }
            }
        }
        return saleOrders;
    }

    @Override
    public List<SaleOrder> querySaleRefundOrderList(String startDate, String endDate) {
        List<SaleOrder> saleOrders = new ArrayList<>();
        saleOrders = saleOrderMapper.queryRefundOrderList(startDate, endDate);
        if (!CollectionUtils.isEmpty(saleOrders)) {
            for (SaleOrder saleOrder : saleOrders) {
                 List<OrderDetail> orderDetails = saleOrderMapper.queryOrderDetailList(saleOrder.getOrderNo());
                 if (!CollectionUtils.isEmpty(orderDetails)) {
                    saleOrder.setOrderDetailList(orderDetails);
                }
            }
        }
        return saleOrders;
    }
}
